package com.xiaoxin.executor.batch.listener;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class EtlStepLogListener<I, O> implements StepExecutionListener {
	private static Logger logger = LogManager.getLogger(EtlStepLogListener.class);

	public void beforeStep(StepExecution stepExecution) {
		String stepName = stepExecution.getStepName();
		Date startTime = stepExecution.getStartTime();
		logger.info("Step begin. [stepName:{}] [startTime:{}]", stepName, startTime);
	}

	public ExitStatus afterStep(StepExecution stepExecution) {
		String stepName = stepExecution.getStepName();
		BatchStatus status = stepExecution.getStatus();
		Date lastUpdated = stepExecution.getLastUpdated();
		logger.info("Step end. [stepName:{}] [status:{}] [lastUpdated:{}]", stepName, status, lastUpdated);

		List<Throwable> failureExceptions = stepExecution.getFailureExceptions();
		for (Throwable exception : failureExceptions) {
			logger.error(exception.getMessage(), exception);
		}
		return null;
	}

}
